package com.lmscn.lms.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.lmscn.lms.api.interceptor.CollectionCondition;
import com.lmscn.lms.api.interceptor.MyCourseCondition;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.DateUtil;
import com.lmscn.lms.api.util.DesEncryptionUtil;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.commons.GlobalConst;

import java.util.*;

/**
 * Created by Czl on 2015/7/25.
 */
public class CourseStudentController extends Controller {

	public CollectionCondition collectionCondition;
	public MyCourseCondition myCourseCondition;

	/**
	 * 下载，点赞，收藏，转发接口
	 */
	@Before(Tx.class)
	public void operateCourse() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		Long courseId = getParaToLong("courseId");
		String type = getPara("type");
		CourseBase courseBase = CourseBase.dao.findById(courseId);
		CourseLesson courseLesson = courseBase.getCourseLesson();
		CourseStudentStatus courseStudentStatus = getModel(CourseStudentStatus.class);
		if (type.equals("1")) { // 下载
			if (CourseStudentStatus.dao.getCourseStudentStatus(courseId, studentId, type) == null) {
				courseLesson.set("download_num", courseLesson.getInt("download_num") + 1).update();
				dataMap.put("error_code", "0");
				dataMap.put("msg", "下载成功");
				CourseStudentStatus.dao.save(courseStudentStatus, courseId, studentId, type);
			} else {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "您已下载");
			}
		} else if (type.equals("2")) { // 点赞
			if (CourseStudentStatus.dao.getCourseStudentStatus(courseId, studentId, type) == null) {
				courseBase.set("ckgood_num", courseBase.getInt("ckgood_num") + 1).update();
				dataMap.put("error_code", "0");
				dataMap.put("msg", "点赞成功");
				CourseStudentStatus.dao.save(courseStudentStatus, courseId, studentId, type);
			} else {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "已点过赞");
			}
		} else if (type.equals("3")) {// 收藏
			if (CourseStudentStatus.dao.getCourseStudentStatus(courseId, studentId, type) == null) {
				courseBase.set("collection_num", courseBase.getInt("collection_num") + 1).update();
				dataMap.put("error_code", "0");
				dataMap.put("msg", "收藏成功");
				CourseStudentStatus.dao.save(courseStudentStatus, courseId, studentId, type);
			} else {
				dataMap.put("error_code", "1");
				dataMap.put("msg", "已收藏");
			}
		} else if (type.equals("4")) { // 转发
			courseBase.set("share_num", courseBase.getInt("share_num") + 1).update();
			dataMap.put("error_code", "0");
			dataMap.put("msg", "转发成功");
		} else {
			dataMap.put("error_code", "1");
			dataMap.put("msg", "参数信息不正确");
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 我的收藏 我的下载
	 * 
	 * 之前是收藏和下载的区分，分别为type为1和3； 修改为三种类型的收藏；
	 * 
	 * @date 2016年12月21日16:41:43
	 */
	@Before(CollectionCondition.class)
	public void collectionCourse() {
		Map<String, Object> dataMapResult = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();

		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		Long studentId = getParaToLong("studentId");
		String type = getPara("type");
		int pageNumber = getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize");

		if (type.equals("1")) {
			// 课程收藏： 状态(1下载，2点赞，3收藏，4转发)
			StringBuilder sql = new StringBuilder();
			List<Object> paras = new ArrayList<Object>();
			collectionCondition.buildCscSql(sql, paras);

			Page<CourseStudentStatus> courseStudentStatusPage = CourseStudentStatus.dao.getCourseCollectionPage(pageNumber,
					pageSize, sql.toString(), paras.toArray());
			List<CourseStudentStatus> courseStudentStatusList = courseStudentStatusPage.getList();

			for (CourseStudentStatus courseStudentStatus : courseStudentStatusList) {
				Map<String, Object> dataMap = new HashMap<String, Object>();
				CourseBase courseBase = CourseBase.dao.findById(courseStudentStatus.getLong("course_id"));
				courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
				courseBase.set("small_img", courseBase.getStr("small_img"));
				courseBase.set("large_img", courseBase.getStr("small_img"));

				dataMap.put("courseBase", courseBase);
				dataMap.put("courseLesson", courseBase.getCourseLesson());
				dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
				dataMapList.add(dataMap);
			}

			data.put("courseList", dataMapList);
			data.put("articleList", null);
			data.put("questionList", null);

		} else if (type.equals("2")) {
			// 资讯收藏：2

			// sql的拼接
			StringBuilder sql = new StringBuilder();
			List<Object> paras = new ArrayList<Object>();

			sql.append("from t_article_student_status t where 1=1 ");
			sql.append(" and student_id = ? ");
			paras.add(studentId);
			sql.append(" and target_type = ? ");
			paras.add(type);
			sql.append(" order by id desc ");

			Page<ArticleStudentStatus> articleStudentStatusPage = ArticleStudentStatus.dao.getArticleCollectionPage(pageNumber,
					pageSize, sql.toString(), paras.toArray());
			List<ArticleStudentStatus> articleStudentStatusList = articleStudentStatusPage.getList();

			List<Article> articleList = new ArrayList<Article>();
			for (ArticleStudentStatus articleStudentStatus : articleStudentStatusList) {
				Map<String, Object> dataMap = new HashMap<String, Object>();
				Article a = Article.dao.getSimpleArticleById(articleStudentStatus.getLong("article_id"));
				String img = a.getStr("img");
				if (img != null && !"".equals(img)) {
					img = CommonUtil.getArticleHeadUrl(img);
				}
				a.set("img", img);

				ArticleCategory ac = ArticleCategory.dao.findById(a.get("category_id"));
				String categoryName = ac.getStr("category_name");

				CategoryColum cc = CategoryColum.dao.getCategoryColumByName(categoryName);
				String cimg = "";
				if (cc != null) {
					cimg = CommonUtil.getCategoryColumimgUrl(cc);
				}

				// ArticleCollection articleCollection = new
				// ArticleCollection();
				// articleCollection.setArticle(a);
				// articleCollection.setColumnImg(cimg);

				a.set("column_img", cimg);

				// dataMap.put("article", a);
				// dataMapList.add(dataMap);

				articleList.add(a);
			}

			data.put("courseList", null);
			data.put("articleList", articleList);
			data.put("questionList", null);

		} else if (type.equals("3")) {
			// 题目收藏：3

			// sql的拼接
			StringBuilder sql = new StringBuilder();
			List<Object> paras = new ArrayList<Object>();

			sql.append("from t_question_favorite t where 1=1 ");
			sql.append(" and student_id = ? ");
			paras.add(studentId);
			sql.append(" order by t.created_time desc ");

			Page<Question> questionPage = Question.dao.getQuestionCollectionPage(pageNumber, pageSize, sql.toString(),
					paras.toArray());
			List<Question> questionList = questionPage.getList();

			List<Question> questionResultList = new ArrayList<Question>();
			for (Question q : questionList) {
				Map<String, Object> dataMap = new HashMap<String, Object>();
				Question question = Question.dao.findById(q.get("question_id"));

				question.set("updated_time", q.get("created_time"));

				// 把选项赋给题目
				List questionMetasList = QuestionMetas.dao
						.getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
				for (int j = 0; j < questionMetasList.size(); j++) {
					QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
					question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
				}

				// dataMap.put("question", question);
				// dataMapList.add(dataMap);
				questionResultList.add(question);
			}

			data.put("courseList", null);
			data.put("articleList", null);
			data.put("questionList", questionResultList);

		}

		dataMapResult.put("error_code", "0");
		dataMapResult.put("msg", "获取成功！");
		dataMapResult.put("data", data);

		renderJson(JsonKit.mapToJson(dataMapResult, 39));
	}

	/**
	 * 删除我的收藏 删除我的下载
	 */
	public void delCollectionCourse() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		String courseIds = getPara("courseIds");
		String type = getPara("type");
		String[] ids = courseIds.split(",");
		int size = 0;
		for (int i = 0; i < ids.length; i++) {

			size = CourseStudentStatus.dao.deleteMyCollection(studentId, Long.parseLong(ids[i]), type);

			CourseBase courseBase = CourseBase.dao.findById(Long.parseLong(ids[i]));
			if (type.equals("3")) {
				if (courseBase.getInt("collection_num") > 0) {
					courseBase.set("collection_num", courseBase.getInt("collection_num") - 1);
					courseBase.update();
				}
			} else {
				CourseLesson courseLesson = courseBase.getCourseLesson();
				if (courseLesson.getInt("download_num") > 0) {
					courseLesson.set("download_num", courseLesson.getInt("download_num") - 1);
					courseLesson.update();
				}
			}
		}
		if (size > 0) {
			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		} else {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "删除失败");
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 批量删除我的收藏
	 * 
	 * 按照收藏的三种类型进行批量的删除；
	 * 
	 * @author zhang.xx
	 * @date 2016年12月22日15:43:28
	 */
	public void delCollection() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		Long studentId = getParaToLong("studentId");
		String idss = getPara("ids");
		String type = getPara("type");

		String[] ids = idss.split(",");

		int size = 0;
		for (int i = 0; i < ids.length; i++) {

			if ("1".equals(type)) {
				// 删除课程收藏 课程收藏类型为1 实际为3；
				type = "3";
				size = CourseStudentStatus.dao.deleteMyCollection(studentId, Long.parseLong(ids[i]), type);
				CourseBase courseBase = CourseBase.dao.findById(Long.parseLong(ids[i]));
				if (courseBase.getInt("collection_num") > 0) {
					courseBase.set("collection_num", courseBase.getInt("collection_num") - 1);
					courseBase.update();
				}
			} else if ("2".equals(type)) {
				// 删除资讯收藏 资讯收藏类型为2
				size = ArticleStudentStatus.dao.deleteMyCollection(studentId, Long.parseLong(ids[i]), type);
				Article article = Article.dao.findById(Long.parseLong(ids[i]));
				if (article.getInt("collection_num") > 0) {
					article.set("collection_num", article.getInt("collection_num") - 1);
					article.update();
				}
			} else if ("3".equals(type)) {
				// 删除题目收藏 题目收藏没有特定的类型数字
				size = QuestionFavorite.dao.deleteMyCollection(Long.parseLong(ids[i]), studentId);

			}
		}

		if (size > 0) {
			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		} else {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "删除失败");
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 添加评论
	 * 
	 * @date 2016年11月19日11:12:35
	 */
	public void courseComment() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		try {
			Long studentId = getParaToLong("studentId");
			Long courseId = getParaToLong("courseId");

			// 评星分数，5分制
			String star = getPara("star");
			float starFloat = Float.parseFloat(star);

			// （1）评星功能
			CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
			CourseBase courseBase = CourseBase.dao.findById(courseId);

			boolean flag = false;
			float oldStarFloat = 0;
			if (courseStudent.get("star") == null) {
				flag = true;
			} else {
				oldStarFloat = courseStudent.get("star");
			}

			// 记录学员选课评分
			courseStudent.set("star", starFloat);
			courseStudent.update();

			if (flag) {
				// new
				// 记录课程评分总分
				courseBase.set("star_num", courseBase.get("star_num") != null ? Float.parseFloat(courseBase.get("star_num") + "")
						+ starFloat : starFloat);
				// 设置评分人数
				courseBase.set("star_stu_num", courseBase.getInt("star_stu_num") == null ? 1
						: courseBase.getInt("star_stu_num") + 1);
				courseBase.update();
			} else {
				// new - old
				courseBase.set("star_num", courseBase.getFloat("star_num") - oldStarFloat + starFloat);
				courseBase.update();
			}

			// （2）评论功能
			if (!(getPara("content") == null || getPara("content").equals(""))) {
				String content = getPara("content");

				Comment comment = getModel(Comment.class);
				Student student = Student.dao.findById(studentId);
				Comment.dao.saveComment(comment, "course", courseId, studentId, content, student.getStr("name"),
						DesEncryptionUtil.decryptStr(student.getStr("post")), student.getStr("little_img"));
			}

			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		} catch (Exception e) {
			e.printStackTrace();
			dataMap.put("error_code", 1);
			dataMap.put("msg", "error");

		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 添加资讯评论
	 * 
	 * @author zhang.xx
	 * @date 2016年12月21日16:51:20
	 */
	public void addArticleComment() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		Long studentId = getParaToLong("studentId");
		Long articleId = getParaToLong("articleId");
		String content = getPara("content");

		Comment comment = getModel(Comment.class);
		Student student = Student.dao.findById(studentId);

		// 评论的type为：article；
		Comment.dao.saveComment(comment, "article", articleId, studentId, content, student.getStr("name"),
				DesEncryptionUtil.decryptStr(student.getStr("post")), student.getStr("little_img"));

		dataMap.put("error_code", 0);
		dataMap.put("msg", "success");
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 评论点赞
	 * 
	 * 课程和资讯的评论点赞功能应该可以通用这个接口；
	 * 
	 * @date 2016年12月21日16:33:23
	 */
	public void ckgComment() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		Long studentId = getParaToLong("studentId");
		Long commentId = getParaToLong("commentId");
		Long courseId = getParaToLong("courseId");

		CourseCommentCkGood courseCommentCkGood = CourseCommentCkGood.dao.getCommentCkGood(courseId, studentId, commentId);

		if (courseCommentCkGood == null) {
			CourseCommentCkGood commentCkGood = getModel(CourseCommentCkGood.class);
			commentCkGood.saveCkGood(commentCkGood, commentId, studentId, courseId);
			Comment comment = Comment.dao.findById(commentId);
			comment.set("ckgood_num", comment.getInt("ckgood_num") + 1);
			comment.update();
			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		} else {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "已点赞啦");
		}

		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 课程评论点赞接口
	 * 
	 * @author zhang.xx
	 * @date 2016年12月21日17:24:59
	 */
	public void ckgArticleComment() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		Long studentId = getParaToLong("studentId");
		Long commentId = getParaToLong("commentId");
		Long articleId = getParaToLong("articleId");

		ArticleCommentCkGood articleCommentCkGood = ArticleCommentCkGood.dao.getCommentCkGood(articleId, studentId, commentId);

		if (articleCommentCkGood == null) {
			ArticleCommentCkGood commentCkGood = getModel(ArticleCommentCkGood.class);
			commentCkGood.saveCkGood(commentCkGood, commentId, studentId, articleId);

			Comment comment = Comment.dao.findById(commentId);
			comment.set("ckgood_num", comment.getInt("ckgood_num") + 1);
			comment.update();

			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		} else {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "已点赞啦");
		}

		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 取消点赞, 取消收藏， 取消评论点赞
	 */
	@Before(Tx.class)
	public void cancelStatus() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long courseId = getParaToLong("courseId");
		Long studentId = getParaToLong("studentId");
		String type = getPara("type");
		if (getPara("commentId") == null || getPara("commentId").equals("")) {
			CourseBase courseBase = CourseBase.dao.findById(courseId);
			if (type.equals("3")) { // 取消收藏
				CourseStudentStatus courseStudentStatus = CourseStudentStatus.dao.getCourseStudentStatus(courseId, studentId,
						type);
				if (courseStudentStatus != null) {
					int flag = CourseStudentStatus.dao.deleteMyCollection(studentId, courseId, type);
					if (flag > 0) {
						if (courseBase.getInt("collection_num") > 0) {
							courseBase.set("collection_num", courseBase.getInt("collection_num") - 1);
							courseBase.update();
						}
						dataMap.put("error_code", 0);
						dataMap.put("msg", "success");
					}
				}
			}
			if (type.equals("2")) { // 取消点赞
				int flag = CourseStudentStatus.dao.deleteMyCollection(studentId, courseId, type);
				if (flag > 0) {
					if (courseBase.getInt("ckgood_num") > 0) {
						courseBase.set("ckgood_num", courseBase.getInt("ckgood_num") - 1);
						courseBase.update();
					}
					dataMap.put("error_code", 0);
					dataMap.put("msg", "success");
				}
			}
		} else {
			if (type.equals("5")) { // 取消评论点赞
				CourseCommentCkGood courseCommentCkGood = CourseCommentCkGood.dao.getCommentCkGood(courseId, studentId,
						Long.parseLong(getPara("commentId")));
				Comment comment = Comment.dao.findById(Long.parseLong(getPara("commentId")));
				if (CourseCommentCkGood.dao.deleteById(courseCommentCkGood.getLong("id"))) {
					if (comment.getInt("ckgood_num") > 0) {
						comment.set("ckgood_num", comment.getInt("ckgood_num") - 1);
						comment.update();
					}
					dataMap.put("error_code", 0);
					dataMap.put("msg", "success");
				}
			}
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 资讯的取消收藏，取消点赞，取消评论点赞
	 * 
	 * 参照：cancelStatus 接口
	 * 
	 * @date 2016年12月22日15:01:44
	 */
	@Before(Tx.class)
	public void cancelArticleStatus() {
		Map<String, Object> dataMap = new HashMap<String, Object>();

		Long articleId = getParaToLong("articleId");
		Long studentId = getParaToLong("studentId");
		String type = getPara("type");

		if (getPara("commentId") == null || getPara("commentId").equals("")) {

			Article article = Article.dao.findById(articleId);

			// 1是点赞；2是收藏；
			if (type.equals("2")) {
				// 取消收藏
				ArticleStudentStatus articleStudentStatus = ArticleStudentStatus.dao.getArticleStudentStatus(articleId,
						studentId, type);
				if (articleStudentStatus != null) {
					int flag = ArticleStudentStatus.dao.deleteMyCollection(studentId, articleId, type);
					if (flag > 0) {
						if (article.getInt("collection_num") > 0) {
							article.set("collection_num", article.getInt("collection_num") - 1);
							article.update();
						}

						dataMap.put("error_code", 0);
						dataMap.put("msg", "success");
					}
				}
			}
			if (type.equals("1")) {
				// 取消点赞
				int flag = ArticleStudentStatus.dao.deleteMyCollection(studentId, articleId, type);
				if (flag > 0) {
					if (article.getInt("ckgood_num") > 0) {
						article.set("ckgood_num", article.getInt("ckgood_num") - 1);
						article.update();
					}

					dataMap.put("error_code", 0);
					dataMap.put("msg", "success");
				}
			}
		} else {
			if (type.equals("5")) {
				// 取消评论点赞

				ArticleCommentCkGood articleCommentCkGood = ArticleCommentCkGood.dao.getCommentCkGood(articleId, studentId,
						Long.parseLong(getPara("commentId")));
				Comment comment = Comment.dao.findById(Long.parseLong(getPara("commentId")));

				if (ArticleCommentCkGood.dao.deleteById(articleCommentCkGood.getLong("id"))) {
					if (comment.getInt("ckgood_num") > 0) {
						comment.set("ckgood_num", comment.getInt("ckgood_num") - 1);
						comment.update();
					}

					dataMap.put("error_code", 0);
					dataMap.put("msg", "success");
				}
			}
		}

		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 选课
	 */
	@Before(Tx.class)
	public void selectedCourse() {
		Map<String, Object> dataMap = new HashMap<String, Object>();
		Long studentId = getParaToLong("studentId");
		Long courseId = getParaToLong("courseId");
		String studyGroup = getPara("studyGroup");
		Long topicId = getParaToLong("topicId");
		
		CourseStudent courseStudent = null;
		CourseTopic courseTopic = null;
		Long studyPlanId = null;
		CourseBase courseBase = CourseBase.dao.findById(courseId);
		if (topicId!=null && topicId>0) {
			courseTopic = CourseTopic.dao.getCourseTopicById(topicId);
			if (courseTopic!=null) {
				studyPlanId = courseTopic.getLong("study_plan_id");
				courseStudent = CourseStudent.dao.getCourseTopicCourseStudent(
						studyPlanId, topicId, courseId, studentId, "studyplan");
			}
		} else {
			courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
		}
		if (topicId!=null && topicId>0 && courseTopic==null) {
			dataMap.put("error_code", 3);
			dataMap.put("msg", "专题不存在");
		} else if (courseBase==null) {
			dataMap.put("error_code", 2);
			dataMap.put("msg", "课程不存在");
		} else if (courseStudent != null) {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "已经选过此门课程");
		} else {
			CourseStudent courseStu = getModel(CourseStudent.class);
			String courseType = studyPlanId==null ? "0" : courseType(studyPlanId, courseId);
			CourseStudent.dao.saveCourseStudent(courseStu, courseId,
					studentId, studyPlanId, "studyplan", courseType, topicId, studyGroup);
			
			// 处理富媒体课程，选课即通过 2017年3月10日10:19:07
			if ("4".equals(courseBase.getCourseLesson().getStr("assemble_type"))) {
				courseStu.set("is_passed", 1);
				courseStu.update();
			}

//			Long courseStudentId = courseStu.getLong("id");
//			CourseStudentProgress csp = getModel(CourseStudentProgress.class);
//			CourseStudentProgress.dao.saveCourseStudentProgress(csp, courseStudentId, courseId, studentId);
//			LessonStudent lessonStudent = getModel(LessonStudent.class);
//			LessonStudent.dao.saveLessonStudent(lessonStudent, courseStudentId,
//					courseId, studentId, courseBase.getCourseLesson().getLong("id"));
			
			
			Map<String, Object> data = new HashMap<String, Object>();
			data.put("courseStudentId", courseStu.getLong("id"));
			dataMap.put("data", data);
			dataMap.put("error_code", 0);
			dataMap.put("msg", "success");
		}
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}
	
	public String courseType(long studyPlanId, long courseId) {
		List<CourseTopic> courseTopicList = CourseTopic.dao.getCourseTopicList(studyPlanId);
		if (courseTopicList==null || courseTopicList.size()==0) {
			return "0";
		}
		String courseIds = "";
		String[] ary = null;
		for (CourseTopic topic : courseTopicList) {
			courseIds = topic.getStr("course_ids");
			if (courseIds==null || "".equals(courseIds)) {
				continue;
			}
			if (Arrays.asList(courseIds.split(",")).contains(courseId+"")) {
				return "1";
			}
		}
		
		return "0";
	}
	
	/**
	 * 我的课程
	 */
	public void myCourse() {
		Integer studentId = getParaToInt("studentId");
		int status = getParaToInt("status"); // 0 未完成  1 已完成
		int type = getParaToInt("type");     // 0选修课  1必修课  -1全部
		
		if (studentId==null || studentId.intValue()<1) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("error_code", 1);
			dataMap.put("msg", "用户ID空");
			renderJson(JsonKit.mapToJson(dataMap, 39));
			return ;
		}
		
		int study_plan_year = Integer.parseInt(DateUtil.getYear());
		Student student = Student.dao.findById(studentId);
		StudyPlan currentStudyPlan = StudyPlan.dao.getStudyPlan(
				study_plan_year, student.getStr("study_group"));
		
		List<CourseStudent> courseStudents = null;
		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		
		if (currentStudyPlan!=null) {
			courseStudents = CourseStudent.dao.findCourseStudentList(
					(long)studentId.intValue(), currentStudyPlan.getLong("id"), "studyplan", status, type);
		}
		
		if (courseStudents!=null && courseStudents.size()>0) {
			for (CourseStudent cs : courseStudents) {
				Map<String, Object> dataMap = new HashMap<String, Object>();
				CourseBase courseBase = CourseBase.dao.findById(cs.getLong("course_id"));
//				courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
				courseBase.set("small_img", courseBase.getStr("small_img"));
				courseBase.set("large_img", courseBase.getStr("small_img"));
//				if (CourseStudentStatus.dao.getCourseStudentStatus(cs.getLong("course_id"),
//						(long)studentId.intValue(), "1") != null) {
//					dataMap.put("download", 1);
//				} else {
//					dataMap.put("download", 0);
//				}
				dataMap.put("courseBase", courseBase);
				dataMap.put("courseLesson", courseBase.getCourseLesson());
				dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
				dataMap.put("courseStudent", cs);
				dataMapList.add(dataMap);
			}
		}
		
		renderJson(JsonKit.listToJson(dataMapList, 39));
	}

	
	
	/**
	 * 我的课程
	@Before(MyCourseCondition.class)
	public void myCourse() {
		Long studentId = getParaToLong("studentId");
		int pageNumber = getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize");
		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		StringBuilder sql = new StringBuilder();
		List<Object> paras = new ArrayList<Object>();
		myCourseCondition.buildCscSql(sql, paras);
		Page<CourseStudent> courseStudentPage = CourseStudent.dao.findCourseStudentPage(pageNumber, pageSize, sql.toString(),
				paras.toArray());
		List<CourseStudent> courseStudents = courseStudentPage.getList();
		for (CourseStudent cs : courseStudents) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			CourseBase courseBase = CourseBase.dao.findById(cs.getLong("course_id"));
			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
			courseBase.set("small_img", courseBase.getStr("small_img"));
			courseBase.set("large_img", courseBase.getStr("small_img"));
			if (CourseStudentStatus.dao.getCourseStudentStatus(cs.getLong("course_id"), studentId, "1") != null) {
				dataMap.put("download", 1);
			} else {
				dataMap.put("download", 0);
			}
			dataMap.put("courseBase", courseBase);
			dataMap.put("courseLesson", courseBase.getCourseLesson());
			dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
			dataMap.put("courseStudent", cs);
			dataMapList.add(dataMap);
		}
		renderJson(JsonKit.listToJson(dataMapList, 39));
	}
**/
	/**
	 * 获取我的课程 中选修课，必修课的数目
	 */
	public void getCourseCount() {
		Long studentId = getParaToLong("studentId");
		Map<String, Object> dataMapCount = new HashMap<String, Object>();
		Long unfinishedXuan = CourseStudent.dao.findCountMyCourse(studentId, "0", 0);
		Long unfinishedBi = CourseStudent.dao.findCountMyCourse(studentId, "1", 0);
		Long finishedXuan = CourseStudent.dao.findCountMyCourse(studentId, "0", 1);
		Long finishedBi = CourseStudent.dao.findCountMyCourse(studentId, "1", 1);
		dataMapCount.put("unFinishedXuan", unfinishedXuan);
		dataMapCount.put("unFinishedBi", unfinishedBi);
		dataMapCount.put("finishedXuan", finishedXuan);
		dataMapCount.put("finishedBi", finishedBi);
		renderJson(JsonKit.mapToJson(dataMapCount, 39));
	}

	/**
	 * 删除我的课程
	 */
	@Before(Tx.class)
	public void delMyCourse() {
		Long studentId = getParaToLong("studentId");
		Long csId = getParaToLong("courseStudentID");
		Map<String, Object> dataMap = new HashMap<String, Object>();
		
		CourseStudent courseStudent = CourseStudent.dao.findById(csId);
		if (courseStudent==null) {
			dataMap.put("error_code", 2);
			dataMap.put("msg", "选课信息有误，不能取消选课");
		} else if (courseStudent.getInt("learned_status") == 1) {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "您已经完成本课程，不能取消选课");
		} else {
			Long courseId = courseStudent.getLong("course_id");
			CourseLesson courseLesson = CourseLesson.dao.findByCourseId(courseId);
//			CourseLearningSetting courseLearningSetting = CourseLearningSetting.dao.findByCourseId(courseId);
			LessonStudentRecord.dao.deleteLessonStudentRecord(csId, courseId, studentId, courseLesson.getLong("id"));
			boolean flag = CourseStudent.dao.deleteById(csId);
			CourseCount.dao.addStudyNumByCourseId(courseId, -1);
			
//			if ("0".equals(courseLearningSetting.getStr("type"))) {
//			}
			
			if (flag) {
				dataMap.put("error_code", 0);
				dataMap.put("msg", "success");
			} else {
				dataMap.put("error_code", 1);
				dataMap.put("msg", "failed");
			}
		}
		
		renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
	}

	/**
	 * 听课计时
	 * 
	 * @date 2016年11月21日09:53:31
	 */
	@Before(Tx.class)
	public void watchCourse() {
		Long watchId = getParaToLong("watchId");
		Long courseId = getParaToLong("courseId");
		Long studentId = getParaToLong("studentId");
		int learnedTimes = getParaToInt("learnedTimes");
		int learnedLocation = getParaToInt("learnedLocation");   // 断点位置
		Map<String, Object> dataMap = new HashMap<String, Object>();

		CourseBase courseBase = CourseBase.dao.findById(courseId);
		CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
		if (courseStudent != null) {
			//课件观看记录信息
			LessonStudentRecord lessonStudentRecord = LessonStudentRecord.dao.findById(watchId);
			Long nowtime = System.currentTimeMillis();
			int validPlaySeconds = Long.valueOf(
					(nowtime - lessonStudentRecord.getDate("learned_starttime").getTime()) / 1000
					).intValue();
			
			//单次播放时长180分钟，不再计时
			if (validPlaySeconds > 180*60) {
				dataMap.put("msg", "播放超过180分钟，不再计时");
			} else {
				// 更新学习记录
				updateStudyAboutLessonStudentRecord(lessonStudentRecord, validPlaySeconds, learnedLocation);
				updateStudyAboutCourseStudent(courseStudent, courseBase, learnedTimes);
				dataMap.put("msg", "success");
			}
			dataMap.put("error_code", 0);
		} else {
			dataMap.put("error_code", 1);
			dataMap.put("msg", "您还未选课");
		}
		
		renderJson(JsonKit.mapToJson(dataMap, 39));
	}

	public void updateStudyAboutLessonStudentRecord(LessonStudentRecord lessonStudentRecord,
			int validPlaySeconds, int learnedLocation) {
		
		lessonStudentRecord.set("learned_endtime", new Date());        // 观看停止时间
		lessonStudentRecord.set("learned_hour", validPlaySeconds);     // 观看时间长度（秒）
		lessonStudentRecord.set("learned_position", learnedLocation);  // 当前观看到的位置
		lessonStudentRecord.update();
	}
	
	public void updateStudyAboutCourseStudent(CourseStudent courseStudent,
			CourseBase courseBase, int time) {
		
		long learnedHour = courseStudent.getLong("learned_hour");  // 观看时长 分钟数
		learnedHour = learnedHour + time;
		courseStudent.set("learned_hour", learnedHour);          // 更新观看时长
		courseStudent.set("last_learned_hour", learnedHour);
		
		if(learnedHour >= courseBase.getInt("minutes")){			
			courseStudent.set("learned_status", 1);
			courseStudent.set("finished_time", new Date());
		}
		courseStudent.update();
	}
	
	
	/**
	 * 听课计时
	 */
	@Before(Tx.class)
	public void watchCourse1() {
		Long courseId = getParaToLong("courseId");
		Long studentId = getParaToLong("studentId");
		int learnedTimes = getParaToInt("learnedTimes");// 课件学习时常
		String endTime = getPara("endTime");// 视频暂停或关闭时时常
		LessonStudentRecord lessonStudentRecord = LessonStudentRecord.dao.findByCourseIdAndStudentId(courseId, studentId);
		CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
		CourseBase courseBase = CourseBase.dao.findById(courseId);
		Map<String, Object> dataMap = new HashMap<String, Object>();
		if (endTime == null) {
			if (lessonStudentRecord != null) {
				lessonStudentRecord.set("learned_hour", learnedTimes + lessonStudentRecord.getInt("learned_hour"));
			}
		} else {
			if (lessonStudentRecord != null) {
				lessonStudentRecord.set("learned_hour", Integer.valueOf(endTime) + lessonStudentRecord.getInt("learned_hour"));
			}
		}
		lessonStudentRecord.update();
		if (lessonStudentRecord != null) {
			if (courseStudent != null) {
				if (courseStudent.getInt("learned_hour") + learnedTimes > courseBase.getInt("minutes")) {
					courseStudent.set("learned_status", 1);
					courseStudent.set("learned_hour", courseBase.getInt("minutes"));
					courseStudent.set("finished_time", new Date());
				} else {
					courseStudent.set("learned_hour", courseStudent.getInt("learned_hour") + learnedTimes);
				}
				courseStudent.update();
				dataMap.put("error_code", 0);
				dataMap.put("msg", "success");
			} else {
				dataMap.put("error_code", 1);
				dataMap.put("msg", "您还未选课");
			}
		}
		renderJson(JsonKit.mapToJson(dataMap, 39));
	}

//	/**
//	 * 初始化听课计时（t_lesson_student_record表新增一条数据）
//	 */
//	public void InitializeWatchCourse() {
//		Long courseId = getParaToLong("courseId");
//		Long studentId = getParaToLong("studentId");
//		String ip = getPara("ip");
//		CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
//		CourseLesson courseLesson = CourseLesson.dao.findByCourseId(courseId);
//		Map<String, Object> dataMap = new HashMap<String, Object>();
//		LessonStudentRecord lessonStudentRecord = getModel(LessonStudentRecord.class);
//		try {
//			LessonStudentRecord.dao.save(lessonStudentRecord, courseStudent.getLong("id"), courseId, studentId,
//					courseLesson.getLong("id"), ip);
//			dataMap.put("lessonStudentRecord", lessonStudentRecord);
//			dataMap.put("success", "初始化成功！");
//		} catch (Exception e) {
//			dataMap.put("error", "初始化失败！");
//		}
//
//		renderJson(JsonKit.mapToJson(dataMap, 39));
//	}
}
